﻿if (typeof Contact == 'undefined') { var Contact = {}; }
if (typeof EmailTemplate == 'undefined') { var EmailTemplate = {}; }
if (typeof EmailList == 'undefined') { var EmailList = {}; }
if (typeof EmailListContact == 'undefined') { var EmailListContact = {}; }
if (typeof Schedule == 'undefined') { var Schedule = {}; }
if (typeof Modal == 'undefined') { var Modal = {}; }
if (typeof Loader == 'undefined') { var Loader = {}; }

/*Loader*/

Loader.Initialize = function () {
}

Loader.Show = function (component) {

    component.parent().append('<img class="Loader" src="Styles/images/Loader.gif" alt="Loader" />');

    Loader.Settings = { Component: $(".Loader") };

    Loader.Settings.SelectedComponent = component;

    Loader.Settings.SelectedComponent.hide();
}

Loader.Hide = function () {
    Loader.Settings.Component.remove();

    Loader.Settings.SelectedComponent.show();
}

/*Modal*/

Modal.Initialize = function () {

    Modal.Settings = { Component: $("#dialog-modal") };

    Modal.Settings.Component.dialog({
        autoOpen: false,
        height: 140,
        modal: true
    });
}

Modal.Open = function () {
    Modal.Settings.Component.dialog('open');
}

/*Contact*/

Contact.Settings = { Components: { Name: undefined, Email: undefined} };

Contact.Initialize = function () {

    Contact.Settings = { Components: { Name: $("#ContactName"), Email: $("#ContactEmail")} };

    clientWS.invoke("GetContacts", { req: {} }, Contact.Success, Contact.Error);

    $("#ContactSave").click(function () {
        if (Contact.Validate()) {

            Loader.Show($(this));

            var data = { "Name": $("#ContactName").val(), "Email": $("#ContactEmail").val(), "Id": 0, "Active": true };

            Contact.Save(data);
        }
    });

    $("#Contacts .Edit").live("click", function () {
        var ctrl = $(this);

        var register = Contact.Data.Contacts.first(function (c) { return c.Id == ctrl.attr("registerid"); });

        var brothers = ctrl.parent().children();

        brothers.each(function () {
            var brother = $(this);

            if (ctrl.attr("crudstatus") == "Edit") {
                var text = brother.text();

                if (!brother.attr("registerid")) {
                    brother.text("");
                    brother.append("<input type='text' value='" + text + "' />");
                }

                brother.attr("crudstatus", "Save");

                $(".EditIcon", brother).hide();
                $(".SaveIcon", brother).show();
            }
            else {
                var text = $('input', brother).val();

                if (!brother.attr("registerid"))
                    brother.text(text);
                else {
                    Loader.Show(ctrl);

                    var status = true;

                    if (brothers.eq(2).text() == "Inativo")
                        status = false;

                    var data = { "Id": brother.attr("registerid"), "Name": brothers.eq(0).text(), "Email": brothers.eq(1).text(), "Active": status };

                    Contact.Save(data);
                }

                brother.attr("crudstatus", "Edit");

                $(".EditIcon", brother).show();
                $(".SaveIcon", brother).hide();
            }
        });
    });
}

Contact.Validate = function () {

    var success = true;

    var validates = [];

    validates.push({ Function: Util.CheckLength, Parameter: { Name: "Nome", Component: Contact.Settings.Components.Name, Min: 2, Max: 20} });
    validates.push({ Function: Util.IsEmail, Parameter: { Name: "E-mail", Component: Contact.Settings.Components.Email} });

    var errors = [];

    for (var i = 0; i < validates.length; i++) {

        var res = validates[i].Function(validates[i].Parameter);

        errors.push(res);

        if (!res.Success)
            success = false;
    }

    Util.Error(errors, $("#ContactError"));

    if (success)
        return true;

    return false;
}

Contact.Save = function (data) {
    clientWS.invoke("SaveContact", { req: { Contacts: [{ "Name": data.Name, "Email": data.Email, "Id": data.Id, "Active": data.Active}]} }, Contact.SaveSuccess, Contact.Error);
}

Contact.SaveSuccess = function (data) {
    if (data) {
        if (data.Contacts.length > 0) {
            var contact = data.Contacts[0];

            var register = Contact.Data.Contacts.first(function (c) { return c.Id == contact.Id });

            if (register) {
                register.Active = contact.Active;
                register.Name = contact.Name;
                register.Email = contact.Email;
            }
            else
                Contact.Data.Contacts.push(contact);

            Contact.Success(Contact.Data);
        }

        if (data.Errors.length > 0)
            Contact.Error(data);
    }

    Loader.Hide();
}

Contact.Success = function (data) {

    Contact.Data = data;

    if (data) {

        $("#Contacts tbody").empty();

        $("#EmailList-Contacts .Contacts ul").empty();

        for (var i = 0; i < data.Contacts.length; i++) {
            var contact = data.Contacts[i];

            var status = "Inativo";

            if (contact.Active)
                status = "Ativo";

            $("#Contacts tbody").append("<tr><td>" + contact.Name + "</td><td>" + contact.Email + "</td><td>" + status + "</td><td class='Edit' RegisterId='" + contact.Id + "' crudstatus='Edit'><img class='EditIcon' src='Styles/images/Edit.png' /><img class='SaveIcon' src='Styles/images/Save.png' style='display:none;' /></td></tr>");

            $("#EmailList-Contacts .Contacts ul").append("<li RegisterId='" + contact.Id + "' class='ln-a'><a>" + contact.Name + "</a></li>");
        }
    }
}

Contact.Error = function (data) {

    var html = "<ul>";

    for (var i = 0; i < data.Errors.length; i++) {
        html += "<li>" + data.Errors[i].FriendlyMessage + "</li>";
    }

    html += "</ul>";

    Modal.Settings.Component.html(html);

    Modal.Open();
}

/*EmailTemplate*/

EmailTemplate.Settings = { Components: { Name: undefined} };

EmailTemplate.Initialize = function () {
    clientWS.invoke("GetTemplates", { req: {} }, EmailTemplate.Success, EmailTemplate.Error);

    $("#add").click(function () {
        var data = { "Id": 0, "Name": $("#name").val(), "Body": $("#body").val(), "Active": true };

        EmailTemplate.Save(data);
    });

    $("#showHide").click(function () {
        $('form').slideToggle('slow');
        //$(this).text("Cadastrar Template");
    });
}

EmailTemplate.Save = function (data) {
    clientWS.invoke("SaveTemplate", { req: { EmailTemplates: [{ "Id": data.Id, "Name": data.Name, "Body": data.Body, "Active": data.Active}]} }, EmailTemplate.SaveSuccess, EmailTemplate.Error);
}

EmailTemplate.SaveSuccess = function (data) {
    if (data && data.EmailTemplates.length > 0) {
        var emailTemplate = data.EmailTemplates[0];

        var register = Contact.Data.EmailTemplates.first(function (et) { return et.Id == emailTemplate.Id });

        if (register) {
            register.Active = emailTemplate.Active;
            register.Name = emailTemplate.Name;
            register.Email = emailTemplate.Email;
        }
        else
            EmailTemplate.Data.EmailTemplates.push(emailTemplate);

        EmailTemplate.Success(EmailTemplate.Data);
    }
}

EmailTemplate.Success = function (data) {

    EmailTemplate.Data = data;

    if (data) {
        for (var i = 0; i < data.length; i++) {
            var template = data[i];

            var status = "Inativo";

            if (template.Active)
                status = "Ativo";

            $("#EmailTemplates tbody").append("<tr><td>" + template.Name + "</td><td>" + status + "</td><td class='Edit'><img src='Styles/images/Edit.png' /></td></tr>");
        }
    }
}

EmailTemplate.Error = function (data) {
    var teste = "";
}

/*EmailList*/

EmailList.Settings = { Components: { Name: undefined} };

EmailList.Initialize = function () {
    EmailList.Settings = { Components: { Name: $("#EmailListName")} };

    clientWS.invoke("GetEmailLists", { req: {} }, EmailList.Success, EmailList.Error);

    $("#EmailListSave").click(function () {
        if (EmailList.Validate()) {
            Loader.Show($(this));

            var data = { "Id": 0, "Name": $("#EmailListName").val(), "Active": true };

            EmailList.Save(data);
        }
    });

    $("#EmailLists .Edit").live("click", function () {
        var ctrl = $(this);

        var register = EmailList.Data.EmailLists.first(function (c) { return c.Id == ctrl.attr("registerid"); });

        var brothers = ctrl.parent().children();

        brothers.each(function () {
            var brother = $(this);

            if (ctrl.attr("crudstatus") == "Edit") {
                var text = brother.text();

                if (!brother.attr("registerid")) {
                    brother.text("");
                    brother.append("<input type='text' value='" + text + "' />");
                }

                brother.attr("crudstatus", "Save");

                $(".EditIcon", brother).hide();
                $(".SaveIcon", brother).show();
            }
            else {
                var text = $('input', brother).val();

                if (!brother.attr("registerid"))
                    brother.text(text);
                else {
                    Loader.Show(ctrl);

                    var status = true;

                    if (brothers.eq(1).text() == "Inativo")
                        status = false;

                    var data = { "Id": brother.attr("registerid"), "Name": brothers.eq(0).text(), "Active": status };

                    EmailList.Save(data);
                }

                brother.attr("crudstatus", "Edit");

                $(".EditIcon", brother).show();
                $(".SaveIcon", brother).hide();
            }
        });
    });
}

EmailList.Validate = function () {

    var success = true;

    var validates = [];

    validates.push({ Function: Util.CheckLength, Parameter: { Name: "Nome", Component: EmailList.Settings.Components.Name, Min: 2, Max: 20} });

    var errors = [];

    for (var i = 0; i < validates.length; i++) {

        var res = validates[i].Function(validates[i].Parameter);

        errors.push(res);

        if (!res.Success)
            success = false;
    }

    Util.Error(errors, $("#EmailListError"));

    if (success)
        return true;

    return false;
}

EmailList.Save = function (data) {
    clientWS.invoke("SaveEmailList", { req: { EmailLists: [{ "Id": data.Id, "Name": data.Name, "Active": data.Active}]} }, EmailList.SaveSuccess, EmailList.Error);
}

EmailList.SaveSuccess = function (data) {
    if (data) {
        if (data.EmailLists.length > 0) {
            var emailList = data.EmailLists[0];

            var register = EmailList.Data.EmailLists.first(function (c) { return c.Id == emailList.Id });

            if (register) {
                register.Active = emailList.Active;
                register.Name = emailList.Name;
                register.Email = emailList.Email;
            }
            else
                EmailList.Data.EmailLists.push(emailList);

            EmailList.Success(EmailList.Data);
        }

        if (data.Errors.length > 0)
            Contact.Error(data);
    }

    Loader.Hide();
}

EmailList.Success = function (data) {

    EmailList.Data = data;

    if (data) {

        $("#EmailLists tbody").empty();

        $("EmailList-Contacts .EmailList ul").empty();

        for (var i = 0; i < data.EmailLists.length; i++) {
            var emailList = data.EmailLists[i];

            var status = "Inativo";

            if (emailList.Active)
                status = "Ativo";

            $("#EmailLists tbody").append("<tr><td>" + emailList.Name + "</td><td>" + status + "</td><td class='Edit' registerid='" + emailList.Id + "' crudstatus='Edit'><img class='EditIcon' src='Styles/images/Edit.png' /><img class='SaveIcon' src='Styles/images/Save.png' style='display:none;' /></td></tr>");

            $("#EmailList-Contacts .EmailList ul").append("<li registerid='" + emailList.Id + "'>" + emailList.Name + "</li>");
        }
    }
}

EmailList.Error = function (data) {
    var teste = "";
}

/*EmailList*/

EmailListContact.Settings = { Components: { Name: undefined} };

EmailListContact.Initialize = function () {
    EmailList.Settings = { Components: { Name: $("#EmailListName")} };

    clientWS.invoke("GetEmailListContacts", { req: {} }, EmailListContact.Success, EmailListContact.Error);

    $("#EmailListContactAdd li").live("click", function () {
        var ctrl = $(this);

        ctrl.siblings().removeClass("selected");

        ctrl.addClass("selected");
    });

    $("#ContactsListNav li").live("click", function () {
        var ctrl = $(this);

        //ctrl.siblings().removeClass("selected");

        if (ctrl.hasClass("selected"))
            ctrl.removeClass("selected");
        else
            ctrl.addClass("selected");
    });

    $("#EmailListContactSave").click(function () {
        Loader.Show($(this));

        $("#EmailListContacts").children().each(function () {
            alert($(this).attr("registerid"));
        });

        EmailListContact.Save(data);
    });
}

EmailListContact.Save = function () {
    clientWS.invoke("SaveEmailListContact", { req: { EmailLists: [{ "Id": data.Id, "Name": data.Name, "Active": data.Active}]} }, EmailList.SaveSuccess, EmailList.Error);
}

EmailListContact.Success = function (data) {

    EmailListContact.Data = data;

    if (data) {

        $("#EmailLists tbody").empty();

        $("EmailList-Contacts .EmailList ul").empty();

        if (data.EmailLists) {

            for (var i = 0; i < data.EmailLists.length; i++) {
                var emailList = data.EmailLists[i];

                var status = "Inativo";

                if (emailList.Active)
                    status = "Ativo";

                $("#EmailLists tbody").append("<tr><td>" + emailList.Name + "</td><td>" + status + "</td><td class='Edit' registerid='" + emailList.Id + "' crudstatus='Edit'><img class='EditIcon' src='Styles/images/Edit.png' /><img class='SaveIcon' src='Styles/images/Save.png' style='display:none;' /></td></tr>");

                $("#EmailList-Contacts .EmailList ul").append("<li registerid='" + emailList.Id + "'>" + emailList.Name + "</li>");
            }
        }
    }
}

EmailListContact.Error = function (data) {
    var teste = "";
}

EmailListContact.SelectContacts = function (emailListId) {
    


};

/*Schedule*/

Schedule.Initialize = function (data) {
    $("#SendDate").datepicker({
        'dateFormat': 'dd/mm/yy',
        'minDate': new Date(),
        dayNames: formatter.daysOfWeek[formatter.culture],
        dayNamesMin: formatter.daysOfWeekMin[formatter.culture],
        dayNamesShort: formatter.daysOfWeekShort[formatter.culture],
        monthNames: formatter.monthNames[formatter.culture],
        monthNamesShort: formatter.monthNamesShort[formatter.culture],
        showOn: "button",
        buttonImage: "Styles/images/Calendar.png",
        buttonImageOnly: true
    });
}